<template>
  <div class="app-container">
    <div class="control-panel">
      <el-button @click="trainButtonClick">🚂 {{isAddingTrain? "完成放置" : "放置火车"}}</el-button>
      <el-button @click="resetView">🔄 还原视图</el-button>
      <span class="status">{{ statusText }}</span>
    </div>
    <el-row :gutter="20">

      <el-col :span="24">
        <div id="container" ref="container">
          <svg id="svg-container" ref="svg_container" xmlns="http://www.w3.org/2000/svg"
               style="width: 33.1102in;height: 23.3858in;" viewBox="0 0 2383.94 1683.78" :style="{
          transform: `translate(${viewState.x}px, ${viewState.y}px) scale(${viewState.scale})`,
          cursor: svgCursor
        }">
            <image id="background" :href="drawingUrl" width="100%" preserveAspectRatio="xMidYMid meet"></image>
            <line
              v-for="line in lines"
              class="svg-line"
              :line-code="line.lineCode"
              :line_name="line.lineName"
              :data-id="line.id"
              :key="line.id"
              :x1="line.x1"
              :y1="line.y1"
              :x2="line.x2"
              :y2="line.y2"

              :stroke="line.color">
            </line>
          </svg>
        </div>
      </el-col>
    </el-row>
    <div id="trainTypePanel" ref="trainTypePanel">
      <div class="train-type-option" data-type="1">🚂 货运列车（红色）</div>
      <div class="train-type-option" data-type="2">🚄 高速列车（蓝色）</div>
      <div class="train-type-option" data-type="3">🚇 地铁列车（绿色）</div>
    </div>
  </div>

</template>

<script>
import {getStation_drawingByUser} from "@/api/system/station_drawing"
import {control} from "@/api/system/catenary_switch"

import {
  getLinesByDrawingId
} from "@/api/system/single_line_annotation";


export default {
  name: "stockyard_control",
  data() {
    return {
      // 遮罩层
      loading: true,
      //
      drawingInfo: {},
      statusText: '就绪',
      svgCursor: '',
      drawingUrl: '',
      viewState: {x: 0, y: 0, scale: 1},
      isDragging: false,
      lastX: 0,
      lastY: 0,
      isAnnotating: false,
      lines: [],
      isAddingTrain: false,
    }
  },
  computed: {
    container() {
      return this.$refs.container
    },
    svgContainer() {
      return this.$refs.svg_container
    },
    trainTypePanel(){
      return this.$refs.trainTypePanel
    }

  },
  mounted() {
    this.container.addEventListener('wheel', this.containerWheel, true); //滚轮缩放
    this.svgContainer.addEventListener('mousedown', this.svgContainerMousedown, true); // 拖拽
    document.addEventListener('mousemove', (e) => {
      if (!this.isDragging) return;
      this.viewState.x = e.clientX - this.lastX;
      this.viewState.y = e.clientY - this.lastY;
    });
    document.addEventListener('mouseup', () => {
      this.isDragging = false;
      this.svgCursor = this.svgCursor ? 'crosshair' : 'grab';
    });
  },
  beforeMount() {
    // window.addEventListener('resize', this.updateTransform)
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.updateTransform)
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据 获取站点图纸
    initData() {
      getStation_drawingByUser().then(response => {
        if (response?.data && response.data.length >= 1) {
          this.drawingUrl = process.env.VUE_APP_BASE_API + response.data[0].basicDrawingInfo;
          this.drawingInfo = response.data[0];
          this.getLines();
        }

      })
    },
    getLines() {
      getLinesByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if (response?.data) {
          this.lines = response.data;
        }
      })
    },
    // 添加火车按钮点击事件
    trainButtonClick() {
      console.log("trainButtonClick",this.isAddingTrain)
      if (this.isAddingTrain) {
        this.exitAddTrainMode();
      } else {
        this.enterAddTrainMode();
      }
    },
    // 取消添加模式
    exitAddTrainMode() {
      this.isAddingTrain = false;
      this.svgCursor = 'grab';
      this.svgContainer.removeEventListener('click', this.handleAddTrainClick);
      this.statusText = "整备场预览模式";
    },
    // 进入添加火车模式
    enterAddTrainMode() {
      this.isAddingTrain = true;
      this.svgCursor = 'crosshair';
      this.svgContainer.addEventListener('click', this.handleAddTrainClick);
      this.statusText = "点击路线添加小火车";
    },
    handleAddTrainClick(e) {
      console.log("handleAddTrainClick",e)
      const point = this.screenToSvg(e.clientX, e.clientY);
      let closestDist = Infinity;
      let closestPoint = null;
      let closestLine = null;

      for (const seg of this.lines) {
        const proj = this.getClosestPointOnSegment(point.x, point.y, seg.x1, seg.y1, seg.x2, seg.y2);
        const dist = Math.hypot(proj.x - point.x, proj.y - point.y);
        if (dist < closestDist) {
          closestDist = dist;
          closestPoint = proj;
          closestLine = seg;
        }
      }

      if (closestDist > 30) {
        alert("请点击靠近路线的位置添加小火车！");
        return;
      }

      this.showTrainTypePanel(e.clientX, e.clientY, closestPoint.x, closestPoint.y);
    },
    showTrainTypePanel(screenX, screenY, svgX, svgY) {
      this.trainTypePanel.dataset.preventClose = 'true'; // 防止立即关闭
      this.trainTypePanel.style.display = 'block';
      this.trainTypePanel.style.left = (screenX + 10) + 'px';
      this.trainTypePanel.style.top = (screenY + 10) + 'px';
      this.trainTypePanel.dataset.svgX = svgX;
      this.trainTypePanel.dataset.svgY = svgY;
    },
    hideTrainTypePanel() {
      this.trainTypePanel.style.display = 'none';
      delete this.trainTypePanel.dataset.preventClose;
    },
    // ========== 坐标转换 ==========
    screenToSvg(clientX, clientY) {
      const pt = this.svgContainer.createSVGPoint();
      pt.x = clientX;
      pt.y = clientY;
      const svgP = pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
      return {
        x: svgP.x,
        y: svgP.y
      }
    },
    getClosestPointOnSegment(px, py, x1, y1, x2, y2) {
      const dx = x2 - x1;
      const dy = y2 - y1;
      const lengthSq = dx * dx + dy * dy;
      if (lengthSq === 0) return { x: x1, y: y1 };
      let t = ((px - x1) * dx + (py - y1) * dy) / lengthSq;
      t = Math.max(0, Math.min(1, t));
      return { x: x1 + t * dx, y: y1 + t * dy };
    },
    containerWheel(e) { // 中心底图缩放事件

      e.preventDefault();
      const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
      const newScale = this.viewState.scale * scaleFactor;

      if (newScale < 0.3 || newScale > 10) return;

      const rect = this.container.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      this.viewState.x -= (mouseX - this.viewState.x) * (scaleFactor - 1);
      this.viewState.y -= (mouseY - this.viewState.y) * (scaleFactor - 1);
      this.viewState.scale = newScale;
    },
    svgContainerMousedown(e) { // 中心底图拖拽事件
      if (this.isAnnotating || e.target.classList.contains('line')) return;
      this.isDragging = true;
      this.lastX = e.clientX - this.viewState.x;
      this.lastY = e.clientY - this.viewState.y;
      this.svgCursor = 'grabbing';
    },
    resetView() { // 还原试图
      this.viewState = {x: 0, y: 0, scale: 1};
    },

  }
}
</script>

<style scoped lang="scss">
body {
  margin: 0;
  padding: 20px;
  font-family: Arial, sans-serif;
  overflow: hidden;
}

#container {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  overflow: hidden;
  position: relative;
  touch-action: none;
}

#svg-container {
  width: 100%;
  height: 100%;
  cursor: grab;
  background-color: #f8f8f8;
}

#svg-container:active {
  cursor: grabbing;
}
/* 火车类型选择面板 */
#trainTypePanel {
  display: none;
  position: absolute;
  background: white;
  border: 1px solid #ccc;
  padding: 10px;
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.svg-line {
  stroke-width: 6;
  stroke: red;
  fill: none;
}

.svg-line:hover {
  stroke-width: 8;
  stroke: aqua;
}

.temp {
  stroke: blue;
  stroke-dasharray: 4, 4;
}

.control-panel {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

button {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

select, input {
  padding: 8px;
  font-size: 14px;
}

.status {
  font-size: 14px;
  color: #555;
  margin-left: auto;
}
</style>
